import { ref } from "vue";
import { register } from '@/api/user.api';
import { omit, pick } from 'lodash-es';
import { useI18n } from 'vue-i18n';
import { sendCode } from '@/api/user.api';

export function useFormState() {
  const { t } = useI18n();
  const formRef = ref();
  const formState = ref({
    phoneOrEmail: '',
    captcha: '',
    password: '',
    confirmPassword: '',
    sendType: 1,
    type: 'register',
  });
  const rules = {
    phoneOrEmail: [
      {
        required: true,
        errorMessage: t('register.form.email.validate.required'),
      },
      {
        format: 'email',
        errorMessage: t('register.form.email.validate.required'),
      }
    ],
    captcha: [
      {
        required: true,
        errorMessage: t('register.form.captcha.validate.required'),
      }
    ],
    password: [
      {
        required: true,
        errorMessage: t('register.form.password.validate.required'),
      }
    ],
    confirmPassword: [
      {
        required: true,
        errorMessage: t('register.form.confirmPassword.validate.required'),
      },
      {
        validateFunction: function (rule, value, data, callback) {
          if (data.confirmPassword !== data.password) {
            callback(t('register.form.confirmPassword.validate.required'))
          }
          return true
        }
      }
    ]
  }



  const handleSubmit = () => {

    formRef.value.validate().then(res => {
      register(omit(formState.value, ['confirmPassword', 'type'])).then(() => {
        uni.showToast({
          title: '倒计时结束后再发送',
            icon: 'success',
        })
        uni.redirectTo({
          url: '/pages/email/index',
        })
      })
    }).catch(errors => {
      uni.showToast({
        title: '倒计时结束后再发送'
      });
    })
  }

  return {
    formRef,
    formState,
    rules,
    handleSubmit
  }

}



export function useAuthCode(formState) {
  const { t } = useI18n();
  const countdown = ref(0)
  const codeHint = ref('获取验证码');


  function startCountdown() {
    countdown.value = 60;
    const timer = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value -= 1;

        codeHint.value = `${countdown.value}秒后重新发送`;
      } else {
        clearInterval(timer);
        codeHint.value = '获取验证码';
      }
    }, 1000);
  }

  function handleSendCode() {
    if (countdown.value > 0) {
      return
    }
    startCountdown()
    sendCode(pick(formState.value, ['phoneOrEmail', 'sendType', 'type']))
  }

  return {
    countdown,
    codeHint,
    handleSendCode
  }
}